import { acceptHMRUpdate, defineStore } from 'pinia'
import { store } from '../index'
import { storageLocal } from '@/utils/storage'
import { decodeAES, encodeAES, aesKey, iv } from '@/utils/aesRsa'
import { StorageEnum } from '@/enums/storageEnums'
import { systemConfigEnum, locale, acceptLanguage } from '@/enums/systemConfigEnums'

export const useSystemConfigStore = defineStore('systemConfig', () => {
  const { CK_SYSTEM_SETTING_STORE, CK_LOCALE_STORE } = StorageEnum
  const systemConfig = ref(null)
  const language = ref('')

  const getSystemConfigCache = () => {
    if (storageLocal.getItem(CK_SYSTEM_SETTING_STORE)) {
      systemConfig.value = JSON.parse(decodeAES(storageLocal.getItem(CK_SYSTEM_SETTING_STORE), aesKey, iv))
    } else {
      systemConfig.value = systemConfigEnum
      setSystemConfigCache()
    }
    if (systemConfig.value.device === 'mobile') {
      systemConfig.value.layout = 'vertical'
    }
  }

  const setSystemConfigCache = () => {
    storageLocal.setItem(CK_SYSTEM_SETTING_STORE, encodeAES(systemConfig.value, aesKey, iv))
  }

  const getLanguageCache = () => {
    if (localStorage.getItem(CK_LOCALE_STORE)) {
      const res = localStorage.getItem(CK_LOCALE_STORE)
      const index = acceptLanguage.findIndex((v) => v === locale)
      if (index === -1) {
        language.value = res
        setLanguageCache()
      } else {
        language.value = localStorage.getItem(CK_LOCALE_STORE)
      }
    } else {
      language.value = locale
      setLanguageCache()
    }
  }

  const setLanguageCache = () => {
    localStorage.setItem(CK_LOCALE_STORE, language.value)
  }

  getSystemConfigCache()
  getLanguageCache()

  return {
    language,
    systemConfig,
    getSystemConfigCache,
    setSystemConfigCache,
    getLanguageCache,
    setLanguageCache
  }
})

// pinia默认不使用热更新，容易报错 ReferenceError: Cannot access ‘...‘ before initialization
if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useSystemConfigStore, import.meta.hot))
}

export const useSystemConfigStoreWithOut = () => {
  return useSystemConfigStore(store)
}
